package com.yunxin.download.server.infra.support.mybatis;


import cn.hutool.core.text.CharSequenceUtil;
import com.yunxin.download.server.infra.utils.AesUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @author zero°
 * @since 2023-05-25
 */
public class AesEncryptHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String s, JdbcType jdbcType) throws SQLException {
        ps.setString(i, AesUtils.X.encrypt(s));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (CharSequenceUtil.isBlank(columnValue)) {
            return columnValue;
        }
        return AesUtils.X.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (CharSequenceUtil.isBlank(columnValue)) {
            return columnValue;
        }
        return AesUtils.X.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (CharSequenceUtil.isBlank(columnValue)) {
            return columnValue;
        }
        return AesUtils.X.decrypt(columnValue);
    }
}
